package org.rohmh.user;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.rohmh.security.domain.Authorities;
import org.rohmh.security.domain.Users;
import org.rohmh.security.service.AuthoritiesService;
import org.rohmh.security.service.UserService;
import org.rohmh.user.domain.Member;
import org.rohmh.user.service.MemberService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


/**
 * Handles requests for the application welcome page.
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private Logger logger = org.slf4j.LoggerFactory.getLogger(UserController.class);

	private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    @Autowired
    private AuthoritiesService securityAuthorityService;

    @Autowired
    private UserService securityUserService;

    @Autowired
    private MemberService umanjiUserService;

	/**
	 * Simply selects the welcome view to render by returning void and relying
	 * on the default request-to-view-translator.
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelMap login(ModelMap model) {
		logger.info("login page !");

		ModelMap mav = new ModelMap();
        mav.addObject("message", "Hello World!");
        return mav;
	}

	@RequestMapping(value = "/update/{userId}", method = RequestMethod.GET)
	public void updateUserForm(@PathVariable String userId, ModelMap model) {
		logger.info("update user form!");
	}

	@RequestMapping(value = "/update/{userId}", method = RequestMethod.POST)
	public void updateUser(ModelMap model) {
		logger.info("update user!");
	}

	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public ModelAndView createUser() {
		logger.info("register user form!");

		Member umanji_member = new Member( new Users() );
        ModelAndView mav = new ModelAndView();
        mav.setViewName("user/createForm");
        mav.addObject("member", umanji_member);
        return mav;

	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@ModelAttribute("member") Member umanji_member, BindingResult result) {
		logger.info("register user!");
		logger.info("register email : " + umanji_member.getEmailAddress());

		umanji_member.getUser().setEnabled(true);
		securityUserService.persist(umanji_member.getUser());
		//create 'user' role authority for this user
        Authorities authorities = new Authorities();
        authorities.setUsername(umanji_member.getUser());
        authorities.setAuthority("ROLE_USER");
        securityAuthorityService.persist(authorities);

        for (ConstraintViolation<Member> constraint : validator.validate(umanji_member)) {
            result.rejectValue(constraint.getPropertyPath().toString(), "", constraint.getMessage());
        }
        if (result.hasErrors())
        	return "user/create";

        umanji_member.setUser(umanji_member.getUser());
        umanji_member.setVersion(new Long(1234234));
        umanjiUserService.persist(umanji_member);
        return "redirect:/user/" + umanji_member.getUser().getUsername();
	}

	@RequestMapping(value = "/delete/{userId}", method = RequestMethod.POST)
	public void delete(@PathVariable String userId, ModelMap model) {
		logger.info("delete user!");
	}
}
